package com.cool.reggie.config;

import com.cool.reggie.core.interceptor.GlobalBeanSerializerModifier;
import com.cool.reggie.utils.JacksonObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Author ifredomvip@gmail.com
 * @Date 2022/6/30 16:31
 * @Version 1.0.0
 * @Description
 **/
@Slf4j
//@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /**
     * 添加资源处理程序
     *
     * @param registry 注册表
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("进行静态资源映射");
        registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
        registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
    }

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        // 条件越多，限制越紧
        // ? 如何查看请求得接口地址 ip
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                // 是否允许发送Cookie信息
                .allowCredentials(true)
                // 是否允许携带请求头信息
                .allowedHeaders("*")
                // 允许哪些 http 方法访问
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                // 有效时长
                .maxAge(3600);
    }

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

        ObjectMapper objectMapper = new ObjectMapper();

        // 将返回字段为null的进行置空处理
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new GlobalBeanSerializerModifier()));
        // 序列化返回数据
        messageConverter.setObjectMapper(new JacksonObjectMapper());

        converters.add(0, messageConverter);
    }
}
